@echo off
setlocal enabledelayedexpansion

:: 获取WSL2的IP地址
for /f "tokens=1 delims= " %%i in ('wsl hostname -I 2^>nul') do set WSL_IP=%%i
if not defined WSL_IP (
    echo 错误：无法获取WSL2 IP地址，请确认WSL正在运行
    pause
    exit /b 1
)
echo WSL2 IP Address: %WSL_IP%

:: 定义端口映射列表，格式为 宿主机端口:WSL2端口
set "PORT_MAPPINGS=80:80,2222:2222"
set "ALL_PORTS="
:: 遍历端口映射列表
for %%p in (%PORT_MAPPINGS%) do (
    for /f "tokens=1,2 delims=:" %%a in ("%%p") do (
        set HOST_PORT=%%a
        set WSL_PORT=%%b
        echo Mapping host port !HOST_PORT! to WSL port !WSL_PORT!

        :: 删除相同端口的现有映射规则
        netsh interface portproxy delete v4tov4 listenport=!HOST_PORT! listenaddress=0.0.0.0 >nul 2>&1
        netsh interface portproxy delete v4tov4 listenport=!HOST_PORT! listenaddress=:: >nul 2>&1

        :: 添加新端口映射
        netsh interface portproxy add v4tov4 listenport=!HOST_PORT! listenaddress=0.0.0.0 connectport=!WSL_PORT! connectaddress=%WSL_IP%

        :: 收集所有端口用于防火墙规则
        if defined ALL_PORTS (
            set "ALL_PORTS=!ALL_PORTS!,!HOST_PORT!"
        ) else (
            set "ALL_PORTS=!HOST_PORT!"
        )
    )
)
:: 删除同名防火墙规则（如果存在）
netsh advfirewall firewall delete rule name="WSL Port" >nul 2>&1

:: 添加包含所有端口的新防火墙规则
netsh advfirewall firewall add rule name="WSL Port" dir=in action=allow protocol=TCP localport=%ALL_PORTS%


: 打印映射结果
echo.
echo Current port mappings:
netsh interface portproxy show v4tov4
echo.
echo Firewall rules:
netsh advfirewall firewall show rule name="WSL Port"
echo.

echo Port mapping and firewall rules setup completed.
pause